$(function() {
  /* video,audio */
  var html='<div class="video" id="multimedia_video" style="display:none;z-index:999;">';
  html+='<div class="multimedia_object" style="width:100%;height:100%">';
  html+='<object id="object" style="z-index:-1;" classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95" controls="controls">';
  html+='<param name="FileName" value="" />';
  html+='<param name="wmode" value="opaque" />';
  html+='<param name="windowlessVideo" value="1" />';
  // html+='<embed id="embed" src="" windowlessVideo="1" allowfullscreen="false" showcontrols="1" autoplay="true"></embed>';
  html+='<video id="embed" src="" controls="controls" autoplay="true" controlslist="nodownload"></video>';
  html+='</object></div><div class="multimedia_close" ><img src="img/close.png" class="multimedia_close" /></div>';
  html+='</div>';
  $("body").prepend(html);
  /* 关闭全屏 */
  $("#multimedia_video .multimedia_close").on("click",function(){
    $("body").css("overflow","auto");
    $("#multimedia_video").hide();
    if(window.ActiveXObject){
      document.getElementById("object").stop();
    }else{
    }
    addMultimedia()
  })

  /* images */
  //其他图片的全屏显示
  var imgHtml='<div id="outerdiv" style=" touch-action: none;position: fixed; top: 0; left: 0;position: fixed;background: rgba(0,0,0,0.8); z-index: 999; width: 100%; height: 100%; display: none;">';
    //imgHtml+='<div id="img_mask"></div>';
    imgHtml+='<div class="img_close"><img class="img_close" src="img/close.png" onclick="closeImgShow()" /></div>';
    imgHtml+='<div id="innerdiv" style="position: absolute;">';
    imgHtml+='<img id="bigimg" src="" style="background-color:#FFFFFF;" /></div></div>';
  $("body").prepend(imgHtml);

    //svg图片的全屏显示
  var svgHtml='<div id="svgouterdiv" style="position: fixed;top: 0; left: 0; z-index: 999; width: 100%; height: 100%; display: none;">';
    svgHtml+='<div class="img_close"><img class="img_close" src="img/close.png" onclick="closeSvgShow()" /></div>';
    svgHtml+='<div id="svginnerdiv" style="position: absolute;width:100%;height:100%;">';
    svgHtml+='<object data="" onload="zoomSvg(this)" id="bigsvg" type="image/svg+xml" style="width:100%;height:100%;background-color:#FFFFFF;"></object>';
    svgHtml+='</div></div>';
  $("body").prepend(svgHtml);

});
/* 图片拖拽 */
 //传入的必须是jQuery对象，否则不能调用jQuery的自定义函数
function drag1() {
  var gapX = 0;
  var gapY = 0;
  var hotImgDiv = document.getElementById('innerdiv');
  // 图片最初大小
  var imgId = document.getElementById("bigimg");
  //PC端对img进行移动操作
  hotImgDiv.addEventListener("mousedown",function(){
    pcStart();
  },false);
  //PC端鼠标开始移动IMG事件函数
  function pcStart(event){
    //兼容event
    var event = event ? event : window.event;
    //判断是否是鼠标左键按下
    if(event.which == 1) {
      gapX = event.clientX - $("#innerdiv").offset().left;
      gapY = event.clientY - $("#innerdiv").offset().top + $(document).scrollTop();
      //movemove事件必须绑定到$(document)上，鼠标移动是在整个屏幕上的
      $(document).bind("mousemove", pcMove);
      //此处的$(document)可以改为obj
      $(document).bind("mouseup", pcStop);
    }
    //阻止默认事件或冒泡
    return false;
  }
  function pcMove(event){
    //兼容event
    var event = event ? event : window.event;
    if(event.which == 1) {
      $("#innerdiv").css({
        "left": (event.clientX - gapX) + "px",
        "top": (event.clientY - gapY) + "px"
      });
    }
    //阻止默认事件或冒泡
    return false;
  }
  function pcStop(event){
    //解绑定
    hotImgDiv.removeEventListener("mousedown",pcStart);
    $(document).unbind("mousemove", pcMove);
    $(document).unbind("mouseup", pcStop);
  }
  //移动端的移动和双指缩放函数
  // hotImgDiv.addEventListener("touchstart",function(){
    appStart();
  // },false);
  function appStart(event) {
    var reqAnimationFrame = (function () {
      return window[Hammer.prefixed(window, 'requestAnimationFrame')] || function (callback) {
        window.setTimeout(callback, 1000 / 60);
      };
    })();
    function point2D(x, y) {
      return {x: x, y: y};
    }
    //x缩放，无，无，y缩放，x平移，y平移
    var tMatrix = [1, 0, 0, 1, 0, 0];
    //初始化scale
    var initScale = 1;
    //获取元素
    var el = document.getElementById('innerdiv');
    var mc = new Hammer.Manager(imgId);
    var ticking = false;
    //缓存双指的中心坐标
    var poscenter = point2D(0, 0);
    //记录上次的偏移值
    var lastTranslate = point2D(0, 0);
    //图像的中心点，用于对比双指中心点
    var lastcenter = point2D(el.offsetWidth / 2, el.offsetHeight / 2);
    var center = lastcenter;
    //开启移动和双指缩放手势
    mc.add(new Hammer.Pan({threshold: 0, pointers: 1}));
    mc.add(new Hammer.Pinch({threshold: 0}));
    //绑定移动和双指缩放手势函数
    mc.on("panstart", onPanStart);
    mc.on("panmove", onPan);
    mc.on("pinchstart", onPinchStart);
    mc.on("pinchmove", onPinch);
    function onPanStart(ev) {
      if(ev.pointerType == "touch"){
        //缓存上一次的偏移值
        lastTranslate = point2D(tMatrix[4], tMatrix[5]);
      }
    }
    function onPan(ev) {
      if(ev.pointerType == "touch"){
        imgId.style.transform = '';
        // el.className = '';
        tMatrix[4] = lastTranslate.x + ev.deltaX;
        tMatrix[5] = lastTranslate.y + ev.deltaY;
        requestElementUpdate('onpan');
      }
    }
    function onPinchStart(ev) {
      if(ev.pointerType == "touch"){
        //记录上一次的偏移值
        lastTranslate = point2D(tMatrix[4], tMatrix[5]);
        initScale = tMatrix[0] || 1;
        poscenter = point2D(ev.center.x, ev.center.y);
        //重新计算放大后的中心坐标
        lastcenter = point2D(center.x + lastTranslate.x, center.y + lastTranslate.y);
        poscenter = point2D(ev.center.x - lastcenter.x, ev.center.y - lastcenter.y);
        requestElementUpdate('onpinchStart');
      }
    }
    function onPinch(ev) {
      if(ev.pointerType == "touch") {
        //限制缩放的范围
        if (initScale * ev.scale > 0.5 && initScale * ev.scale < 20) {
          var nowScale = tMatrix[0] = tMatrix[3] = initScale * ev.scale;
          // var composscal = (1 - ev.scale);
          //tMatrix[4] = poscenter.x - ((poscenter.x - lastcenter.x) *  ev.scale + lastcenter.x)  + lastTranslate.x//最后加上上一次的偏移值
          //tMatrix[5] = poscenter.y - ((poscenter.y - lastcenter.y) *  ev.scale + lastcenter.y)  + lastTranslate.y
          // tMatrix[4] = (1 - ev.scale) * poscenter.x + lastTranslate.x;
          // tMatrix[5] = (1 - ev.scale) * poscenter.y + lastTranslate.y;
          requestElementUpdate('onpinch');
        }
      }
    }
    function updateElementTransform() {
      // mc.style.transition = duration;
      var tmp = tMatrix.join(',');
      imgId.style.transform = 'matrix(' + tmp + ')';
      ticking = false;
    }
    function requestElementUpdate() {
      arguments && console.log("arguments=="+arguments[0])
      if (!ticking) {
        reqAnimationFrame(updateElementTransform);
        ticking = true;
      }
    }
    /**
     初始化设置
     */
    requestElementUpdate();
  }
}
  //初始化放大图片和缩放
function imgShow(outerdiv, innerdiv, bigimg, src, _this) {
  var src = src;//获取当前点击的pimg元素中的src属性
  $(bigimg).attr("src", src);//设置#bigimg元素的src属性
  var windowW = $(window).width();//获取当前窗口宽度
  var windowH = $(window).height();//获取当前窗口高度
  //获取图片真实宽度
  var realWidth = _this.width();
  var realHeight = _this.height();
  if($(_this).attr("width")){
    realWidth = $(_this).attr("width");
    realHeight = $(_this).attr("height");
  }else{
    realWidth = _this.width();
    realHeight = _this.height();
  }
  $(bigimg).css("width", realWidth);//以最终的宽度对图片缩放
  var w = (windowW - realWidth)/2;// 计算图片与窗口左边距
  var h = (windowH - realHeight)/2;// 计算图片与窗口上边距
  //设置图片大小
  $(bigimg).css({
    "width" : realWidth +'px',
    "height" : realHeight +'px'
  });
  //设置#innerdiv的top和left属性
  $(innerdiv).css({
    "top" : h +'px',
    "left" : w +'px'
  });
  //初始化图片比例
  document.getElementById("bigimg").style.transform = 'scale('+ 1 +')';
  console.log(document.getElementById("bigimg"), '$(bigimgbigimgbigimgbigimg)', $(bigimg));
  
  //$(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg //cll ie8下跟position fixed 出现图片闪烁
  $(outerdiv).show();
  drag1();
  //先移除鼠标滚动事件（避免事件叠加），在绑定事件
  $("#outerdiv").off('mousewheel');
  //以鼠标位置为中心的图片滚动放大缩小
  $("#outerdiv").on("mousewheel","#bigimg",function(ev){
    var bigimg = this;
    var ev = event || window.event;//返回WheelEvent
    // ev.preventDefault();
    var delta = ev.detail ? ev.detail > 0 : ev.wheelDelta < 0;
    //获取鼠标在图片上的位置是图片宽度的百分比
    var ratioL = (ev.clientX - $("#innerdiv")[0].offsetLeft) / bigimg.offsetWidth,
      ratioT = (ev.clientY - $("#innerdiv")[0].offsetTop) / bigimg.offsetHeight,
      //获取图片缩放宽高
      ratioDelta = !delta ? 1 + 0.1 : 1 - 0.1,
      w2 = parseInt(bigimg.offsetWidth * ratioDelta),
      h2 = parseInt(bigimg.offsetHeight * ratioDelta),
      //获取图片位置
      l = Math.round(ev.clientX - (w2 * ratioL)),
      t = Math.round(ev.clientY - (h2 * ratioT));
    //限制图片缩放的大小
    if(w2 > realWidth*0.5 && w2 < realWidth*10){
      //设置图片大小
      with(bigimg.style) {
        width = w2 +'px';
        height = h2 +'px';
      }
      //设置图片位置
      $("#innerdiv").css({
        "top":  t +'px',
        "left": l +'px'
      });
    }
  });
}
  //再次点击淡出消失弹出层
  function closeImgShow() {
      //$(this).fadeOut("fast");//cll ie8下跟position fixed 出现图片闪烁
      $(outerdiv).hide();
  };

//全屏显示svg图片
function svgShow(outerdiv, bigimg, src) {
  var src = src;//获取当前点击的pimg元素中的src属性
  //$(bigimg).attr("data", src);//设置#bigimg元素的src属性
  $("#svginnerdiv").html('<object data="' + src + '" id="bigsvg" style="width:100%;height:100%;background-color:#FFFFFF;" type="image/svg+xml"'+
    '" onload="zoomSvg(this)"></object>');
  $(outerdiv).show();
  //xtt修改点击全屏显示图片的放大数值的bug:添加代码$(".zoomm-value").text("100%");
  $(".svg-value").text("100%");

}
//关闭全屏显示svg图片
function closeSvgShow(){
  $("#svgouterdiv").hide();
}
  //初始化SVG
function zoomSvg(obj) {
  // 此处获取的元素Id是SVG文件中的<g>标签的id值
  $(obj.getSVGDocument().getElementById('svg')).show();
  //设置初始化SVG的选项变量
  var svgOperate = {
    zoomEnabled: true, //开启缩放功能
    controlIconsEnabled: true, //开启右下角缩放控件功能
    zoomScaleSensitivity: 0.1,  //每次缩放大小
    dblClickZoomEnabled: false,
    panEnabled: true,   		  // 启用或禁用平移（默认启用）
    mouseWheelZoomEnabled: true,  // 启用或禁用鼠标滚轮缩放（默认启用）
    minZoom: 0.5,
    maxZoom: 20,
    center: true,
    customEventsHandler: {
      //先设置zoompan控件中停止所有的触摸事件
      haltEventListeners: ['touchstart', 'touchend', 'touchmove', 'touchleave', 'touchcancel']
      //再初始化自定义的手势事件来处理程序
      , init: function (options) {
        //初始化图片的大小和坐标
        var instance = options.instance
          , initialScale = 1
          , pannedX = 0
          , pannedY = 0;
        // 初始化Hammer手势，对touch进行JT
        this.hammer = new Hammer(options.svgElement, {
          inputClass: Hammer.SUPPORT_POINTER_EVENTS ? Hammer.PointerEventInput : Hammer.TouchInput
        });

        //double点击
        this.hammer.on('doubletap', function (ev) {
          instance.zoomIn();
        });
        //单指移动
        this.hammer.on('panstart panmove', function (ev) {
          //平移开始
          if (ev.type === 'panstart') {
            pannedX = 0;
            pannedY = 0;
          }
          //重置平移的变量
          instance.panBy({x: ev.deltaX - pannedX, y: ev.deltaY - pannedY});
          pannedX = ev.deltaX;
          pannedY = ev.deltaY;
        });
        //设置启用双指缩放
        this.hammer.get('pinch').set({enable: true});
        //进行两指缩放
        this.hammer.on('pinchstart pinchmove', function (ev) {
          //双指缩放开始时先保存初始化的比例大小，再进行计算
          if (ev.type === 'pinchstart') {
            initialScale = instance.getZoom();
            instance.zoom(initialScale * ev.scale);
          }
          instance.zoom(initialScale * ev.scale);
        });
        //双指缩放开始时先保存初始化的比例大小，再进行计算
        options.svgElement.addEventListener('touchmove', function (e) {
          e.preventDefault();
        });
      }//销毁所有手势操作
      , destroy: function () {
        this.hammer.destroy();
      }
    }
  }
  //初始化SVG
  svgPanZoom(obj, svgOperate);
}
/* 全屏打开 */
function multimediaShow(url){
  $("#multimedia_video").find("#object")[0].FileName =url;
  $("#multimedia_video").find("#embed").attr("src",url);
  $("#embed,#object").attr("width","100%");
  $("#embed,#object").attr("height","100%");
  $("body").css("overflow","hidden");
  $("#multimedia_video").show();
}
function addMultimedia(){
  var html='<object id="object" style="z-index:-1;" classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95" controls="controls">';
  html+='<param name="FileName" value="" />';
  /* html+='<param name="AutoStart" value="0" />'; */
  html+='<param name="wmode" value="opaque" />';
  html+='<param name="windowlessVideo" value="1" />';
  // html+='<embed id="embed" src="" windowlessVideo="1" allowfullscreen="false" showcontrols="1" autoplay="true"></embed>';
  html+='<video id="embed" src=""  controls="controls" autoplay="true" controlslist="nodownload"></video>';

  html+='</object>';
  //html+='<div class="multimedia_close" ><img src="img/close.png" class="multimedia_close" /></div>';

  $(".multimedia_object").html(html);
}
